package com.bobi.tfca.ui.article

import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.navigation.NavOptions
import androidx.navigation.findNavController
import com.bobi.tfca.R
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.ArticleAPI
import com.bobi.tfca.network.api.ResourceAPI
import com.bobi.tfca.network.response.ArticleResponse
import com.bobi.tfca.network.response.ParagraphResponse
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.viewmodel.PublicViewModel
import com.bumptech.glide.Glide
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MultipartBody

class ArticleFragmentVM: ViewModel() {


    val paragraphList by lazy {
        MutableLiveData(ArrayList<ParagraphResponse>())
    }

    /**
     * 将图片上传至服务器，由服务器上传至腾讯云，将返回的地址设为图片地址。
     */
    fun uploadImageToServer(
        fragment: WriteArticleFragment,
        publicViewModel: PublicViewModel,
        file: MultipartBody.Part,
        imageView: ImageView,
        position: Int
    ) {
        publicViewModel.apply {
            request(ResourceAPI::class.java).uploadImage(file).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }
                        ApiResponse.Loading -> LogUtil.e("Loading")

                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data
                                if (result?.code == 200) {
                                    val url = it.data.data ?: ""
                                    if (url.isNotBlank() && (!"null".equals(url))) {
                                        if (fragment.isAdded() && !fragment.isDetached()) {
                                            Glide.with(fragment).load(url)
                                                .placeholder(R.drawable.defaultbg_h).into(imageView)
                                        }
                                    }
                                    // 更改viewmodel的值
                                    paragraphList.value?.get(position)?.picture = url
                                } else {
                                    Toast.makeText( fragment.requireActivity(), "上传失败", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 发布文章，头部信息和段落分开的，方便添加段落，因为addParagraph方法在Adapter里
     */
    fun publishArticle(
        publicViewModel: PublicViewModel,
        fragment: WriteArticleFragment,
        article: ArticleResponse
    ) {
        article.paragraphList = this.paragraphList.value ?: arrayListOf()
        publicViewModel.apply {
            request(ArticleAPI::class.java).publishArticle(article).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                LogUtil.i("发布成功")
                                val articleId = it.data?.data
                                if (articleId != null) {
                                    publicViewModel.article.value!!.articleId = articleId
                                    // 成功后前往文章的详情页面，并弹出该页面
                                    fragment.requireActivity().findNavController(R.id.app_nav).navigate(R.id.showArticleFragment, null,
                                        NavOptions.Builder().setPopUpTo(R.id.writeArticleFragment, true)
                                            .build())
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 获得文章详细内容
     */
    fun getArticleDetails(publicViewModel: PublicViewModel, fragment: ShowArticleFragment) {
        val articleId = publicViewModel.article.value!!.articleId
        publicViewModel.apply {
            request(ArticleAPI::class.java).getArticleDetails(articleId).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val res = it.data?.data
                                if (res != null) {
                                    article.value = res
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 删除文章
     */
    fun deleteArticle(publicViewModel: PublicViewModel, showArticleFragment: ShowArticleFragment) {
        val articleId = publicViewModel.article.value!!.articleId
        publicViewModel.apply {
            request(ArticleAPI::class.java).deleteArticle(articleId).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                // 删除后返回首页
                                publicViewModel.resetArticle()
                                showArticleFragment.requireActivity().findNavController(R.id.app_nav).navigateUp()
                            }
                        }
                    }
                }
            }
        }
    }

    fun likeArticle(
        publicViewModel: PublicViewModel,
        b: Boolean,
        showArticleFragment: ShowArticleFragment
    ) {
        val articleId = publicViewModel.article.value!!.articleId
        publicViewModel.apply {
            request(ArticleAPI::class.java).likeArticle(b, articleId).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val article = publicViewModel.article.value
                                article!!.isLiked = b
                                article.likes
                                if (b) {
                                    article.likes += 1
                                } else {
                                    article.likes -= 1
                                }
                                publicViewModel.article.value = article
                            }
                        }
                    }
                }
            }
        }
    }

}